import { DotLoading, Empty, InfiniteScroll, NavBar, Image as MyImage, Button } from "antd-mobile";
import { useNavigate } from "react-router-dom";
import $fetch from "../../../utils/app/$fetch";
import $reducer from "../../../utils/app/$reducer";
import moment from "moment";
import './style.scss'


const OrderList = () => {
    const initState = {
        orderList: [],
        hasMore: true,
        pageNum: 1,
        pageSize: 5,
        isLoading: false,
        hasLoaded: false,
    };

    const [state, dispatch] = $reducer({ ...initState });
    const navigate: any = useNavigate();

    const loadMore = async () => {
        try {
            if (state?.isLoading) {
                return;
            }
            dispatch({ isLoading: true });
            const res: any = await $fetch(
                "order/list",
                {
                    pageSize: state?.pageSize,
                    pageNum: state?.pageNum,
                    status: -1,
                },
                { loading: false, noGroupId: "no" }
            );
            const hasMore = res?.totalPage > state?.pageNum ? true : false;
            
            res?.list.forEach((item: any)=>{
                const img: any = new Image();
                img.src = item?.goodsPhoto;
            })

            dispatch({
                orderList: state?.orderList.concat(res?.list || []),
                hasMore,
                isLoading: false,
                hasLoaded: true,
                pageNum: state?.pageNum + 1,
            });
        } catch (error) {
            console.log("____");

            dispatch({ hasLoaded: true, hasMore: false });
        }
    };

    const back = () => {
        // window.history.go(-1);
        navigate("/home");
        // navigate("/home", { state: { current: "personal" } });
    };

    const InfiniteScrollContent = ({ hasMore }: { hasMore?: boolean }) => {
        if (hasMore) {
            return (
                <>
                    <span style={{ fontSize: "16px", marginTop: "20px" }}>数据加载中</span>
                    <DotLoading />
                </>
            );
        } else if (state?.orderList?.length > 0) {
            return <span>没有更多数据了</span>;
        }
        return null;
    };

    const renderView = () => {
        if (!state?.hasLoaded) {
            return null;
        }
        if (!state?.orderList?.length) return <Empty description="暂无数据" />;
        return (
            <ul className="that_public_list">
                {state?.orderList.map((list: any) => {
                    return (
                        <li key={list?.skuId}>
                            <div className="item_top">
                                <div>订单编号：{list?.orderSn}</div>
                            </div>
                            {list?.orderItemList.map((item: any) => {
                                return (
                                    <>
                                        <div className="item_bottom">
                                            <MyImage src={item?.goodsPhoto} fit='cover' lazy={true} width='2.13rem' height='2.13rem' />
                                            <div className="right_wraper">
                                                <div className='content'>
                                                    <div>
                                                        <div className="header">
                                                            <div>{item?.goodsName}</div>
                                                            <div>×{item?.goodsQuantity}</div>
                                                        </div>
                                                        {item?.payment !== null && <div  className='method'>领取方式：{item?.payment === 0 ? '电子券' : item?.payment === 1 ? '线下自提' : ''}</div>}
                                                    </div>
                                                    {item?.goodsRedeemed !== null &&
                                                        <div className='code' 
                                                            onClick={() => { 
                                                                if(item?.goodsRedeemed === 1) return;
                                                                navigate('/coupon', { state: { orderSn: item?.orderSn, goodsId: item?.goodsId, from: 'order'}})}
                                                            }
                                                        >
                                                            {<img src={`${item?.goodsRedeemed === 1 ? require('../../../asset/imgs/exchanged.png') : item?.goodsRedeemed === 0 ? require('../../../asset/imgs/unexchange.png') : ''}`} alt="" />}
                                                        </div>}
                                                </div>

                                                <div className="time">下单时间：{moment(list?.orderTime).format("YYYY-MM-DD HH:mm:ss")}</div>
                                                {item?.goodsPoint !== null &&<div className="price core_price">
                                                     积分：<span>- {item?.goodsPoint}</span>
                                                </div>}
                                            </div>
                                        </div>
                                    </>
                                );
                            })}
                            {list?.orderPrice !== null && <div className="price ">
                                订单金额：<span>{list?.orderPrice}</span>
                            </div>}
                        </li>
                    );
                })}
            </ul>
        );
    };

    return (
        <div className="container_order_list">
            <NavBar
                style={{
                    "--border-bottom": "1px #eee solid",
                }}
                onBack={back}>
                我的订单
            </NavBar>
            {renderView()}

            <InfiniteScroll loadMore={loadMore} hasMore={state?.hasMore}>
                <InfiniteScrollContent hasMore={state?.hasMore}></InfiniteScrollContent>
            </InfiniteScroll>
        </div>
    );
};

export default OrderList;
